package com.cyt.work.kwmanagement.service.impl;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.model.po.SysFile;
import com.cyt.sys.model.vo.SysFileVo;
import com.cyt.sys.service.SysFileService;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.sys.util.EntryUtils;
import com.cyt.work.kwmanagement.dao.KwStudentMessageDao;
import com.cyt.work.kwmanagement.model.po.*;
import com.cyt.work.kwmanagement.model.vo.*;
import com.cyt.work.kwmanagement.service.*;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.vo.WxEducationUserVo;
import com.cyt.wx.service.WxEducationUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * 考务学生表-考务学生表Service层实现类
 *
 * @author han jun
 * @date 2019-11-26 11:24:38
 */
@Service("kwStudentMessageService")
public class KwStudentMessageServiceImpl extends BaseServiceImpl<KwStudentMessage> implements KwStudentMessageService {

    @Resource
    private KwStudentMessageDao kwStudentMessageDao;

    @Autowired
    private WxEducationUserService wxEducationUserService;

    @Autowired
    private KwKcSettingService kwKcSettingService;


    @Autowired
    private KwKmMessageService kwKmMessageService;

    @Autowired
    private KwKcMessageService kwKcMessageService;

    @Autowired
    private KwManagementService kwManagementService;

    @Autowired
    private  KwStudentSignService kwStudentSignService;

    @Autowired
    private SysFileService sysFileService;





    @Autowired
    public void setBaseDao(KwStudentMessageDao kwStudentMessageDao) {
        this.baseDao = kwStudentMessageDao;
    }

    /**
     * 查询对象集合
     *
     * @param kwStudentMessageVo 对象
     * @return List 对象集合
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    public List<KwStudentMessage> listExample(KwStudentMessageVo kwStudentMessageVo) {
        Example example = new Example(KwStudentMessage.class);
        example.setOrderByClause(" create_time desc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        if (!StringUtils.isEmpty(kwStudentMessageVo.getApplyId())){
            criteria.andEqualTo("applyId",kwStudentMessageVo.getApplyId());
        }
        if (!StringUtils.isEmpty(kwStudentMessageVo.getId())){
            criteria.andEqualTo("id",kwStudentMessageVo.getId());
        }
        if (!StringUtils.isEmpty(kwStudentMessageVo.getKsId())){
            criteria.andEqualTo("ksId",kwStudentMessageVo.getKsId());
        }
        return kwStudentMessageDao.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param kwStudentMessageVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    public ReturnResult page(KwStudentMessageVo kwStudentMessageVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<KwStudentMessage> list = listExample(kwStudentMessageVo);
        PageInfo<KwStudentMessage> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }


    /**
     * 查询导入的关联的学生
     *
     * @param kwStudentMessageVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    public ReturnResult pageNew(KwStudentMessageVo kwStudentMessageVo, int pageNum, int pageSize) {
        List<KwStudentMessageVo>list  = kwStudentMessageDao.selectVoList(kwStudentMessageVo);
        PageInfo<KwStudentMessageVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @Override
    public ReturnResult pageNewOther(KwStudentMessageVo kwStudentMessageVo, int pageNum, int pageSize) {
        List<KwStudentMessageVo>list  = kwStudentMessageDao.selectVoNewList(kwStudentMessageVo);
        PageInfo<KwStudentMessageVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 查询导入的关联的学生
     *
     * @param kwStudentMessageVo 接受参数对象
     * @return ReturnResult
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    public  List<KwStudentExportVo> exPortStu(KwStudentMessageVo kwStudentMessageVo){
        List<KwStudentMessageVo>list  = kwStudentMessageDao.selectVoNewList(kwStudentMessageVo);
        List<KwStudentExportVo> newList = new ArrayList<>();
        for (KwStudentMessageVo kwStudentMessageVo1:list){
            KwStudentExportVo kwStudentExportVo = new KwStudentExportVo();
            kwStudentExportVo.setExamNum(kwStudentMessageVo1.getExamNum());
            kwStudentExportVo.setKcNum(kwStudentMessageVo1.getName());
            kwStudentExportVo.setUserNumber(kwStudentMessageVo1.getUserNumber());
            kwStudentExportVo.setKcPlace(kwStudentMessageVo1.getKcPlace());
            kwStudentExportVo.setSeatNum(kwStudentMessageVo1.getSeatNum());
            kwStudentExportVo.setStSeatNum(kwStudentMessageVo1.getStSeatNum());
            kwStudentExportVo.setName(kwStudentMessageVo1.getName());
            newList.add(kwStudentExportVo);
        }
        return newList;
    }

    /**
     * 查询学生考试签到情况
     *
     * @param kwStudentMessageVo 接受参数对象
     * @return ReturnResult
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    public ReturnResult studentSignList(KwStudentMessageVo kwStudentMessageVo){
        List<KwStudentMessageVo> list  = kwStudentMessageDao.selectVoList(kwStudentMessageVo);
        KwStudentSignVo kwStudentSignVo = new KwStudentSignVo();
        kwStudentSignVo.setKsId(kwStudentMessageVo.getKsId());
        kwStudentSignVo.setKcId(kwStudentMessageVo.getKcId());
        kwStudentSignVo.setKmId(kwStudentMessageVo.getKmId());
        List<KwStudentSignVo> signVoList = kwStudentSignService.findVoList(kwStudentSignVo);
        for (KwStudentMessageVo kwStudentMessageVo1:list){
            kwStudentMessageVo1.setSignState(kwStudentMessageVo.getSignType());//缺勤
            for (KwStudentSignVo kwStudentSignVo1:signVoList){
                if (kwStudentMessageVo1.getEducationUserid().equals(kwStudentSignVo1.getEducationUserid())){
                    kwStudentMessageVo1.setSignState(kwStudentSignVo1.getSignState());
                    kwStudentMessageVo1.setSignId(kwStudentSignVo1.getId());
                }
            }

        }
        return new ReturnResult(list);
    }








    /**
     * 添加或更新
     *
     * @param kwStudentMessageVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(KwStudentMessageVo kwStudentMessageVo, SysUser sysUser) {
        if (StringUtils.isBlank(kwStudentMessageVo.getId())) {
            KwStudentMessage kwStudentMessage = new KwStudentMessage(sysUser);
            kwStudentMessage.setApplyId(kwStudentMessageVo.getApplyId());
            kwStudentMessage.setKsId(kwStudentMessageVo.getKsId());
            kwStudentMessage.setEducationUserid(kwStudentMessageVo.getEducationUserid());
            kwStudentMessage.setKcId(kwStudentMessageVo.getKcId());
            kwStudentMessage.setSeatNum(kwStudentMessageVo.getSeatNum());
            kwStudentMessage.setStSeatNum(kwStudentMessageVo.getStSeatNum());
            kwStudentMessage.setExamNum(kwStudentMessageVo.getExamNum());
            kwStudentMessageDao.insert(kwStudentMessage);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            KwStudentMessage kwStudentMessage = kwStudentMessageDao.selectByPrimaryKey(kwStudentMessageVo.getId());
            kwStudentMessage.setApplyId(kwStudentMessageVo.getApplyId());
            kwStudentMessage.setKsId(kwStudentMessageVo.getKsId());
            kwStudentMessage.setEducationUserid(kwStudentMessageVo.getEducationUserid());
            kwStudentMessage.setKcId(kwStudentMessageVo.getKcId());
            kwStudentMessage.setSeatNum(kwStudentMessageVo.getSeatNum());
            kwStudentMessage.setStSeatNum(kwStudentMessageVo.getStSeatNum());
            kwStudentMessage.setExamNum(kwStudentMessageVo.getExamNum());
            kwStudentMessage.setUpdateTime(new Date());
            kwStudentMessage.setUpdateUser(sysUser.getId());
            kwStudentMessageDao.updateByPrimaryKey(kwStudentMessage);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }




    /**
     * 根据条件逻辑删除
     *
     * @param kwStudentMessageVo 参数接受对象
     * @param sysUser 当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(KwStudentMessageVo kwStudentMessageVo, SysUser sysUser) {
        //要修改的字段
        KwStudentMessage kwStudentMessage = new KwStudentMessage();
        kwStudentMessage.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        kwStudentMessage.setUpdateUser(sysUser.getId());
        kwStudentMessage.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(KwStudentMessage.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(kwStudentMessageVo.getId())) {
            criteria.andIn("id", Arrays.asList(kwStudentMessageVo.getId().split(",")));
        }
        if (StringUtils.isNotBlank(kwStudentMessageVo.getKsId())) {
            criteria.andEqualTo("ksId", kwStudentMessageVo.getKsId());
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        kwStudentMessageDao.updateByExampleSelective(kwStudentMessage, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param kwStudentMessageVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-11-26 11:24:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(KwStudentMessageVo kwStudentMessageVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(KwStudentMessage.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(kwStudentMessageVo.getId())) {
            criteria.andIn("id", Arrays.asList(kwStudentMessageVo.getId().split(",")));
        }
        kwStudentMessageDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 导入
     * @param file
     * @param sysUser
     * @author hanjun
     * @date 2019/9/3 13:47
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult importExcel(MultipartFile file,String ksId, SysUser sysUser,  String applyId) {
        // 用户表中是否存在数据
        KwStudentMessageVo kwStudentMessageVo = new KwStudentMessageVo();
        kwStudentMessageVo.setKsId(ksId);
        kwStudentMessageVo.setApplyId(applyId);
        List<KwStudentMessage> deleteStudents = listExample(kwStudentMessageVo);
        for (KwStudentMessage KwStudentMessage:deleteStudents){
            KwStudentMessageVo kwStudentMessageVo1 = new KwStudentMessageVo();
            kwStudentMessageVo1.setKsId(KwStudentMessage.getKsId());
            remove(kwStudentMessageVo1,sysUser);
        }
        ExcelImportResult<KwStudentMessageUserVerifyImportVo> result = EasyPoiUtil.importExcelResult(file, 1, 1, KwStudentMessageUserVerifyImportVo.class);
        List<KwStudentMessageUserVerifyImportVo> questionUserList =  result.getList();
        Map<String, KwStudentMessageExportVo> questionUserMap = new HashMap<>();
        String key;
        for (KwStudentMessageExportVo questionUser : questionUserList) {
            key = questionUser.getUserNumber();
            if (questionUserMap.keySet().contains(key)) {
                continue;
            }
            questionUserMap.put(key, questionUser);
        }
        List<WxEducationUser> wxEducationUserList = new ArrayList<>();
        List<WxEducationUser> wxEducationUserShow = new ArrayList<>();
        for (Map.Entry<String, KwStudentMessageExportVo> entry : questionUserMap.entrySet()) {
            KwStudentMessageExportVo userFrom = entry.getValue();
            // 查询账号是否存在
            WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
            wxEducationUserVo.setUserNumber(userFrom.getUserNumber());
            wxEducationUserVo.setCreateUser(sysUser.getId());
            List<WxEducationUser> list = wxEducationUserService.listExample(wxEducationUserVo);
            if (list != null && list.size() > 0) {
                wxEducationUserShow.addAll(list);
                for (WxEducationUser wxEducationUser:list){
                    if (wxEducationUser.getName( )== userFrom.getUserName()){

                    }else {
                        wxEducationUser.setName(userFrom.getUserName());
                        wxEducationUserService.updateByPrimaryKey(wxEducationUser);
                    }
                }
                WxEducationUser wxEducationUser = list.get(0);
                //更新数据库学生的操作
                saveEductionUserList(userFrom,sysUser,wxEducationUser.getId(),ksId,applyId);
                continue;
            }
            // 账号不存在，保存进用户表
            WxEducationUser wxEducationUser = new WxEducationUser();
            wxEducationUser.setId(BaseUtil.uId());
            wxEducationUser.setApplyId(applyId);
            wxEducationUser.setLoginName(userFrom.getUserNumber());
            wxEducationUser.setMobile(userFrom.getMobile());
            wxEducationUser.setName(userFrom.getUserName());
            wxEducationUser.setUserNumber(userFrom.getUserNumber());
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(userFrom.getMobile()) && userFrom.getMobile().length() == 11) {
                wxEducationUser.setPassword(MD5Util.MD5Encode(StrUtil.sub(userFrom.getMobile(), 5, 11)));
            } else {
                wxEducationUser.setPassword(MD5Util.MD5Encode(BaseConstant.DEFAULT_EDUCATION_USER_PASSWORD));
            }
            wxEducationUser.setUserType("3");
            wxEducationUser.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
            wxEducationUser.setCreateUser(sysUser.getId());
            wxEducationUser.setUpdateUser(sysUser.getId());
            wxEducationUser.setCreateTime(new Date());
            wxEducationUser.setUpdateTime(new Date());
            wxEducationUserList.add(wxEducationUser);
            wxEducationUserShow.add(wxEducationUser);
            wxEducationUserService.insert(wxEducationUser);
            saveEductionUserList(userFrom,sysUser,wxEducationUser.getId(),ksId,applyId);

        }

        if (result.isVerfiyFail()) {
            // 如果错误，打印出提醒，直接返回
            int successNum = 0;
            int failNum = result.getFailList().size();
            if (result.getList() != null && result.getList().size() > 0) {
                successNum = result.getList().size();
            }
            String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
            List<KwStudentMessageUserVerifyImportVo> failList = result.getFailList();
            // 需要将成功条数也返回
            Map<String, Object> resutlMap = new HashMap<>();
            resutlMap.put("failList", failList);
            resutlMap.put("successList", wxEducationUserShow);
            return new ReturnResult(ErrorCode.CODE_1, resutlMap, errorMsg);
            //return new ReturnResult(wxEducationUserShow);
        }
        int successNumber =0;
        if (result.getList() != null && result.getList().size() > 0) {
            successNumber = result.getList().size();
        }
        String sucess = String.format("共导入%s条，成功%s条，失败0条。", successNumber, successNumber);
        return new ReturnResult(ErrorCode.CODE_0,successNumber , sucess);
    }

    //新增学生的操作
    private void saveEductionUserList( KwStudentMessageExportVo userFrom,SysUser sysUser,String educationUserId, String ksId,String appId){
        KwStudentMessage kwStudentMessage = new KwStudentMessage(sysUser);
        kwStudentMessage.setApplyId(appId);
        kwStudentMessage.setKsId(ksId);
        kwStudentMessage.setEducationUserid(educationUserId);
        kwStudentMessageDao.insert(kwStudentMessage);

    }


    /**
     * 导入成绩
     * @param file
     * @param sysUser
     * @author hanjun
     * @date 2019/9/3 13:47
     */
    @Override
     public ReturnResult importExcelStudentScore(MultipartFile file,String ksId,SysUser sysUser, String applyId){
        String str = file.getOriginalFilename();
        return new ReturnResult(ErrorCode.CODE_0,str);
    }





    /**
     * 分配学生
     *
     * @param sysUser            用户信息
     * @param kwStudentMessageVo 传入参数对象
     * @return ResultDto
     * @author rong yuan
     * @date 2018-10-27 11:00:07
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult startDistributeStudent(KwStudentMessageVo kwStudentMessageVo,  SysUser sysUser) {
             KwKcSettingVo kwKcSettingVo = new KwKcSettingVo();
             kwKcSettingVo.setKsId(kwStudentMessageVo.getKsId());
             kwKcSettingVo.setApplyId(kwStudentMessageVo.getApplyId());
             KwKcSetting kwKcSetting = kwKcSettingService.listExample(kwKcSettingVo).get(0);
            if (kwKcSetting != null) {
                KwKcMessageVo kwKcMessageVo = new KwKcMessageVo();
                kwKcMessageVo.setKsId(kwStudentMessageVo.getKsId());
                kwKcMessageVo.setApplyId(kwStudentMessageVo.getApplyId());
                List<KwKcMessage> kwKcMessageList = kwKcMessageService.listExample(kwKcMessageVo);
                //参加考试学生信息
                List<KwStudentMessage> kwStudentMessageList = listExample(kwStudentMessageVo);
                if ("0".equals(kwKcSetting.getCjfp())) {
                    distributeStudentByRandom(kwKcMessageList, kwStudentMessageList,"",sysUser);
                } else if ("1".equals(kwKcSetting.getCjfp())) {
                    distributeStudentByRandom(kwKcMessageList, kwStudentMessageList,"",sysUser);
                }
                return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);

        }
        return  new ReturnResult("获取失败");
    }

    private void distributeStudentByRandom(List<KwKcMessage> kwKcMessageList, List<KwStudentMessage> kwStudentMessageList, String applyId,SysUser sysUser) {
        Random rand = new Random();
        //当前年月日
        String currentDate = DateUtil.getDateText(new Date(),"yyyy-MM-dd");
        //当前年份
        String currentYear = DateUtil.getDateText(new Date(),"yyyy");
        //入学年份后两位
        String rxYear = currentDate.substring(2, currentYear.length());
        //准考证4位递增序列号
        int examNum = 1;
        for (int i = 0; i < kwKcMessageList.size(); i++) {
            //两位考场号
            String kcNum = kwKcMessageList.get(i).getKcNum();
            if (kcNum.length() == 1) {
                kcNum = "0" + kcNum;
            }
            //考场人数
            int kcStu = Integer.parseInt(kwKcMessageList.get(i).getKcStu());
            for (int j = 0; j < kcStu; j++) {
                int index = rand.nextInt(kwStudentMessageList.size());
                KwStudentMessage kwStudentMessage = kwStudentMessageList.get(index);
                kwStudentMessage.setKcId(kwKcMessageList.get(i).getId());
                //两位座位号
                String seatNum = String.valueOf(j + 1).length() == 1 ? ("0" + String.valueOf(j + 1)) : String.valueOf(j + 1);
                kwStudentMessage.setSeatNum(seatNum);
                //考场座位号
                String stSeatNum = currentYear + rxYear + kcNum + seatNum;
                kwStudentMessage.setStSeatNum(stSeatNum);
                //准考证号
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(currentDate);
                for (int k = 0; k < 4 - String.valueOf(examNum).length(); k++) {
                    stringBuffer.append("0");
                }
                kwStudentMessage.setExamNum(stringBuffer.append(examNum).toString());
                KwStudentMessageVo kwStudentMessageVo = new KwStudentMessageVo();
                EntryUtils.copyProperties(kwStudentMessage, kwStudentMessageVo);
                addOrUpdate(kwStudentMessageVo,sysUser);
                kwStudentMessageList.remove(index);
                examNum++;
            }
        }
    }

    /**
     * 获取学生准考证信息
     *
     * @param kwStudentMessageVo 传入参数对象
     * @return ResultDto
     * @author hanjun
     * @date 2018-10-27 11:00:07
     *  */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult getExamAttance(KwStudentMessageVo kwStudentMessageVo,WxEducationUser wxEducationUser){
        //获取考场分配信息
        List<KwStudentMessage> kwStudentMessages = listExample(kwStudentMessageVo);
        KwStudentMessage kwStudentMessage = kwStudentMessages.get(0);
        //获取考试科目信息
        KwKmMessageVo kwKmMessageVo = new KwKmMessageVo();
        kwKmMessageVo.setKsId(kwStudentMessageVo.getKsId());
        List<KwKmMessage> kwKmMessageList = kwKmMessageService.listExample(kwKmMessageVo);

        String date = "";
        boolean sw = false;
        boolean xw = false;
        List<Map> list = new ArrayList<>();
        for (int i = 0; i < kwKmMessageList.size(); i++) {
            Map map = new HashMap();
            KwKmMessage kwKmMessage = kwKmMessageList.get(i);
            String beginTime = DateUtil.convertDateToString(DateUtil.DATE_TIME_PATTERN, kwKmMessage.getBeginTime());
            String endTime = DateUtil.convertDateToString(DateUtil.DATE_TIME_PATTERN, kwKmMessage.getEndTime());
            String hour = beginTime.substring(11, 13);

            String d = DateUtil.convertDateToString("yyyy年MM月dd日", kwKmMessage.getBeginTime());
            int dayForWeek = 0;
            try {
                dayForWeek = DateUtil.dayForWeekN(DateUtil.convertDateToString("yyyy-MM-dd", kwKmMessage.getBeginTime()));
            } catch (Exception e) {

            }
            //if (!d.equals(date)) {
                date = "";
                sw = false;
                xw = false;
            //}

            //时间的显示情况
            if (Integer.parseInt(hour) <= 12) {
                if (sw) {
                    map.put("sw", "");
                    map.put("xw", "");
                } else {
                    map.put("sw", "上午：");
                    map.put("xw", "");
                    sw = true;
                    xw = false;
                }
            } else {
                if (xw) {
                    map.put("sw", "");
                    map.put("xw", "");
                } else {
                    map.put("sw", "");
                    map.put("xw", "下午：");
                    sw = false;
                    xw = true;
                }
            }

            if (StringUtils.isBlank(date)) {
                date = d;
                map.put("date", date + "(星期" + getDayForWeek(dayForWeek) + ")");
            } else {
                if (d.equals(date)) {
                    map.put("date", "");
                } else {
                    date = d;
                    map.put("date", date + "(星期" + getDayForWeek(dayForWeek) + ")");
                }
            }
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(beginTime.substring(11, 16));
            stringBuffer.append("-");
            stringBuffer.append(endTime.substring(11, 16));
            stringBuffer.append("，");
            stringBuffer.append(kwKmMessage.getKmmc());
            map.put("kmInfo", stringBuffer.toString());
            //这里做做一个筛选的情况
            list.add(map);
        }
        //对里面所有的元素在进行划分

        List<String> timeString = new ArrayList<>();//时间
        for (Map map:list){
            if (timeString.indexOf(map.get("date"))<0){
                timeString.add((String) map.get("date"));
            }

        }

//        for (String string:timeList){
//            Map map = new HashMap();
//            List<KwTeacherMessageVo> newkwList = new ArrayList<>();
//            for (KwTeacherMessageVo kwTeacherMessageVonew:newList){
//                if (string.equals(kwTeacherMessageVonew.getBeginTime().substring(0,10))){
//                    newkwList.add(kwTeacherMessageVonew);
//                }
//            }
//            map.put("time",string);
//            map.put("list",newkwList);
//            mapList.add(map);
//
//        }

        List<Map> listDate = new ArrayList<>();
        for (String string:timeString){
            List<Map> dataString = new ArrayList<>();
            List<String> dataStringnew = new ArrayList<>();
            Map dataMap = new HashMap();
            for (Map map:list){
                Map newMap = new HashMap();
                if (map.get("date").equals(string)){
                    if (!StringUtils.isEmpty((String) map.get("sw"))){
                        if (dataStringnew.indexOf(map.get("sw"))<0){
                            newMap.put("noon",map.get("sw"));
                            dataStringnew.add((String) map.get("sw"));
                            dataString.add(newMap);
                        }
                    }
                    if (!StringUtils.isEmpty((String) map.get("xw"))){
                        if (dataStringnew.indexOf(map.get("xw"))<0){
                            newMap.put("noon",map.get("xw"));
                            dataStringnew.add((String) map.get("xw"));
                            dataString.add(newMap);
                        }
                    }

                }

            }
            dataMap.put("name",string);
            dataMap.put("date",dataString);
            listDate.add(dataMap);
        }
        //最后要分类到最下面去的情况

           for (Map map:listDate){
               List<Map> kwList =(List<Map>) map.get("date");
                       for (Map map1:kwList){
                           List<Map> liststu = new ArrayList<>();
                           for (Map newMap:list){
                               if (newMap.get("date").equals(map.get("name"))){
                                   if (!StringUtils.isEmpty((String) newMap.get("sw"))){
                                       if (map1.get("noon").equals(newMap.get("sw"))){
                                           liststu.add(newMap);
                                       }

                                   }
                                   if (!StringUtils.isEmpty((String) newMap.get("xw"))){
                                       if (map1.get("noon").equals(newMap.get("xw"))){
                                           liststu.add(newMap);
                                       }

                                   }
                               }
                               map1.put("detail",liststu);

                           }

                       }
                   }











        //获取考场设置信息
        KwKcMessageVo kwKcMessageVo = new KwKcMessageVo();
        kwKcMessageVo.setId(kwStudentMessage.getKcId());
        List<KwKcMessage> kcMessages = kwKcMessageService.listExample(kwKcMessageVo);
        KwKcMessage kwKcMessage = kcMessages.get(0);
        //获取考试设置信息
        KwManagementVo kwManagementVo = new KwManagementVo();
        kwManagementVo.setId(kwStudentMessage.getKsId());
        KwManagement kwManagement = kwManagementService.listExample(kwManagementVo).get(0);

        Map map = new HashMap<>();
        map.put("title", kwManagement.getTitle());
        //获取一寸照片的信息
        SysFileVo sysFileVo = new SysFileVo();
        sysFileVo.setObjectId(wxEducationUser.getObjectidOne());
        List<SysFile> listpic;
        String str ="";
        if (StringUtils.isEmpty(wxEducationUser.getObjectidOne())){
        }else {
            listpic = (List<SysFile>) sysFileService.list(sysFileVo).getData();
            for (SysFile sysFile:listpic){
                sysFile.setPath("/sysFile/showFileByPath?path="+sysFile.getPath());
                str = "/sysFile/showFileByPath?path="+sysFile.getPath();
            }
        }

        map.put("photoPath", str);
        map.put("examNum", kwStudentMessage.getExamNum());
        map.put("name", wxEducationUser.getName());
        map.put("stSeatNum", kwStudentMessage.getStSeatNum());
        map.put("kcNum", kwKcMessage.getKcNum());
        map.put("seatNum", kwStudentMessage.getSeatNum());
        map.put("kwKmMessageList", listDate);
        map.put("remark", StringUtils.isBlank(kwManagement.getRemark()) ? "" : kwManagement.getRemark());
        map.put("kcPlace", kwManagement.getAddress() + (StringUtils.isBlank(kwKcMessage.getKcPlace()) ? "" : kwKcMessage.getKcPlace()));
        //封装获取的信息
        return  new ReturnResult(map);
    }

    private String getDayForWeek(int dayForWeek) {
        String result = "";
        switch (dayForWeek) {
            case 1:
                result = "一";
                break;
            case 2:
                result = "二";
                break;
            case 3:
                result = "三";
                break;
            case 4:
                result = "四";
                break;
            case 5:
                result = "五";
                break;
            case 6:
                result = "六";
                break;
            case 7:
                result = "日";
                break;
        }
        return result;
    }


    /**
     * 获取学生考试的统计
     *
     * @param pageNum 传入参数对象
     * @return ResultDto
     * @author hanjun
     * @date 2018-10-27 11:00:07
     *  */
    @Override
    public ReturnResult getAllStudentStatic(int pageNum, int pageSize){
        KwStudentMessageVo kwStudentMessageVo = new KwStudentMessageVo();
        List<KwStudentMessageVo>list = kwStudentMessageDao.selectVoOtherList(kwStudentMessageVo);
        List<String> strings = new ArrayList<>();
        for (KwStudentMessageVo KwStudentMessageNew : list) {
                if (strings.indexOf(KwStudentMessageNew.getEducationUserid()) < 0) {
                    strings.add(KwStudentMessageNew.getEducationUserid());
                }
            }

        List<KwStudentMessageVo> mapList = new ArrayList<>();
        for (String str : strings) {
            Map map = new HashMap();
            List<KwStudentMessageVo> newList = new ArrayList<>();
            List<KwStudentMessageVo> newListNew = new ArrayList<>();
            for (KwStudentMessageVo kwStudentMessageVo1 : list) {
                if (kwStudentMessageVo1.getEducationUserid().equals(str)) {
                    newList.add(kwStudentMessageVo1);
                }
            }
            for (KwStudentMessageVo kwStudentMessagenew:newList){
                KwStudentSignVo kwStudentSignVo = new KwStudentSignVo();
                kwStudentSignVo.setKsId(kwStudentMessagenew.getKsId());
                kwStudentSignVo.setKcId(kwStudentMessagenew.getKcId());
                kwStudentSignVo.setEducationUserid(str);
                kwStudentSignVo.setKmId(kwStudentMessagenew.getKmId());
                List<KwStudentSignVo> studentSignVos = kwStudentSignService.findVoList(kwStudentSignVo);
                if (studentSignVos.size() == 0) {
                    newListNew.add(kwStudentMessagenew);
                }
            }
            //获取他考试的次数和缺考的次数
            WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
            wxEducationUserVo.setId(str);
            WxEducationUser wxEducationUser = wxEducationUserService.listExample(wxEducationUserVo).get(0);
            KwStudentMessageVo kwTeacherSettingnew = new KwStudentMessageVo();
            kwTeacherSettingnew.setName(wxEducationUser.getName());
            kwTeacherSettingnew.setAttecenExamNum(String.valueOf(newList.size()));
            kwTeacherSettingnew.setAbsentceExamNum(String.valueOf(newListNew.size()));
            kwTeacherSettingnew.setUserNumber(wxEducationUser.getUserNumber());
            mapList.add(kwTeacherSettingnew);
        }

            PageInfo<KwStudentMessageVo> page = new PageInfo<>(mapList);
            return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());

    }



    /**
     * 获取考场学生签到的详情
     *
     * @param pageNum 传入参数对象
     * @return ResultDto
     * @author hanjun
     * @date 2018-10-27 11:00:07
     *  */
    @Override
    public ReturnResult getAllStudentSign(KwStudentMessageVo newKwstudentVo, int pageNum, int pageSize){
        List<KwStudentMessageVo> list = kwStudentMessageDao.selectVoOtherList(newKwstudentVo);
            for (KwStudentMessageVo kwStudentMessageVo1 : list) {
                KwStudentSignVo kwStudentSignVo = new KwStudentSignVo();
                kwStudentSignVo.setKsId(kwStudentMessageVo1.getKsId());
                kwStudentSignVo.setKcId(kwStudentMessageVo1.getKcId());
                kwStudentSignVo.setKmId(kwStudentMessageVo1.getKmId());
                kwStudentSignVo.setEducationUserid(kwStudentMessageVo1.getEducationUserid());
                //获取考试科目的情况

                List<KwStudentSignVo> studentSignVos = kwStudentSignService.findVoList(kwStudentSignVo);
                //全部 已签到 未签到三种
                if (studentSignVos.size() == 0) {
                    kwStudentMessageVo1.setSignState("2");//未签到
                }else {
                    kwStudentMessageVo1.setSignState("1");//已签到
                }

            WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
            wxEducationUserVo.setId(kwStudentMessageVo1.getEducationUserid());
            WxEducationUser wxEducationUser = wxEducationUserService.listExample(wxEducationUserVo).get(0);
            kwStudentMessageVo1.setName(wxEducationUser.getName());

        }
        if (StringUtils.isNotBlank(newKwstudentVo.getSignState())){
            List<KwStudentMessageVo> listNew = new ArrayList<>();
            for (KwStudentMessageVo kwStudentMessageVo:list){
                if (kwStudentMessageVo.getSignState().equals(newKwstudentVo.getSignState())){
                    listNew.add(kwStudentMessageVo);
                }
            }
            if (StringUtils.isNotBlank(newKwstudentVo.getKcState())){
                List<KwStudentMessageVo> listNewOther = new ArrayList<>();
                for (KwStudentMessageVo kwStudentMessageVo:listNew){
                    if (kwStudentMessageVo.getKcNum().equals(newKwstudentVo.getKcState())){
                        listNewOther.add(kwStudentMessageVo);
                    }
                }
                PageInfo<KwStudentMessageVo> page = new PageInfo<>(listNewOther);
                return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());

            }else {
                PageInfo<KwStudentMessageVo> page = new PageInfo<>(listNew);
                return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
            }


        }else {
            if (StringUtils.isNotBlank(newKwstudentVo.getKcState())){
                List<KwStudentMessageVo> otherList = new ArrayList<>();
                for (KwStudentMessageVo kwStudentMessageVo:list){
                    if (kwStudentMessageVo.getKcNum().equals(newKwstudentVo.getKcState())){
                        otherList.add(kwStudentMessageVo);
                    }
                }
                PageInfo<KwStudentMessageVo> page = new PageInfo<>(otherList);
                return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
            }else {
                PageInfo<KwStudentMessageVo> page = new PageInfo<>(list);
                return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
            }

        }

    }
    /**
     * 获取学生统计汇总
     *
     * @return ResultDto
     * @author hanjun
     * @date 2018-10-27 11:00:07
     *  */
    @Override
    public List<KwStudentStaticVo> getAllKsStudent(){
        KwStudentMessageVo kwStudentMessageVo = new KwStudentMessageVo();
        List<KwStudentMessageVo>list = kwStudentMessageDao.selectVoList(kwStudentMessageVo);
        List<String> strings = new ArrayList<>();
        for (KwStudentMessageVo KwStudentMessageNew : list) {
            if (strings.indexOf(KwStudentMessageNew.getEducationUserid()) < 0) {
                strings.add(KwStudentMessageNew.getEducationUserid());
            }
        }

        List<KwStudentStaticVo> mapList = new ArrayList<>();
        for (String str : strings) {
            Map map = new HashMap();
            List<KwStudentMessageVo> newList = new ArrayList<>();
            List<KwStudentMessageVo> newListNew = new ArrayList<>();
            for (KwStudentMessageVo kwStudentMessageVo1 : list) {
                if (kwStudentMessageVo1.getEducationUserid().equals(str)) {
                    newList.add(kwStudentMessageVo1);
                }
                KwStudentSignVo kwStudentSignVo = new KwStudentSignVo();
                kwStudentSignVo.setKsId(kwStudentMessageVo1.getKsId());
                kwStudentSignVo.setKcId(kwStudentMessageVo1.getKcId());
                kwStudentSignVo.setEducationUserid(kwStudentMessageVo1.getEducationUserid());
                List<KwStudentSignVo> studentSignVos = kwStudentSignService.findVoList(kwStudentSignVo);
                if (studentSignVos.size() == 0) {
                    newListNew.add(kwStudentMessageVo1);
                }
            }

            WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
            wxEducationUserVo.setId(str);
            WxEducationUser wxEducationUser = wxEducationUserService.listExample(wxEducationUserVo).get(0);
            KwStudentStaticVo kwStudentStaticVo = new KwStudentStaticVo();
            kwStudentStaticVo.setName(wxEducationUser.getName());
            kwStudentStaticVo.setAttecenExamNum(String.valueOf(newList.size()));
            kwStudentStaticVo.setAbsentceExamNum(String.valueOf(newListNew.size()));
            kwStudentStaticVo.setUserNumber(wxEducationUser.getUserNumber());
            mapList.add(kwStudentStaticVo);
        }
        return  mapList;
    }



}